//
//  MyWalletVC.m
//  MyProject
//
//  Created by jiaming yan on 2018/3/29.
//  Copyright © 2018年 yanjiaming. All rights reserved.
//

#import "MyWalletVC.h"
#import "WalletTransactionTableViewCell.h"
#import "WalletSafeVC.h"
#import "GetCashVC.h"
#import "TransactionListModel.h"
#import "NSUDManager.h"
#import "Masonry.h"
#import "UITableView+Empty.h"

@interface MyWalletVC ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)  NSMutableArray *arrData;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *safeAreaTopHeight;

@end

@implementation MyWalletVC
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorFromRGB(0XF2F5FA);
    self.navigationController.navigationBarHidden = YES;
    // Do any additional setup after loading the view from its nib.
    [self loadTabbleView];
    [self downRefreshRequest];
    [self upRefreshRequest];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshWallet) name:@"refreshWallet" object:nil];
}
-(void)refreshWallet{
    [self.tableView.mj_header beginRefreshing];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self walletMoney];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}
-(void)walletMoney{
     UserModel *user = [NSUDManager currentUser];
    [self.view bringSubviewToFront:self.loadingView];
    self.loadingView.hidden = NO;
    [YJMSendRequest postDataWithParameters:@{@"userId":user.userId} url:@"user/getIncumbentInfo" result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        [self hideProgress:self.view animated:YES];
        if([result[@"result"] integerValue] == 1)
        {
            [self.view sendSubviewToBack:self.loadingView];
            self.loadingView.hidden = YES;
            self.priceLabel.text = [NSString stringWithFormat:@"%@",result[@"data"][@"userInfo"][@"leftBalance"]];
        }else{
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];

}
/*
 方法描述:
 加载列表
 
 参数说明:
 <#参数说明#>
 
 返回结果:
 <#返回结果#>
 
 */
-(void)loadTabbleView{
    [self.tableView registerNib:[UINib nibWithNibName:@"WalletTransactionTableViewCell" bundle:nil] forCellReuseIdentifier:@"WalletTransactionTableViewCell"];
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.estimatedRowHeight = 184.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
   
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.safeAreaTopHeight.constant = 20;
    }
    UIView *aView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 15)];
    aView.backgroundColor = UIColorFromRGB(0XF2F5FA);
    self.tableView.tableHeaderView = aView;
}
#pragma mark ------tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.arrData.count;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return 65;
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    static NSString *identifier = @"WalletTransactionTableViewCell";
    WalletTransactionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.selectionStyle =  UITableViewCellSelectionStyleNone;
    TransactionListModel *model = self.arrData[indexPath.row];
    if ([model.recerdStatus isEqualToString:@"IN"]) {
        /**增加*/
        cell.typeLabel.text = @"+";
        cell.typeLabel.textColor = UIColorFromRGB(0XEF8989);
        cell.priceLabel.textColor = UIColorFromRGB(0XEF8989);
    }else{
        cell.typeLabel.text = @"-";
        cell.typeLabel.textColor = UIColorFromRGB(0X42CDD9);
        cell.priceLabel.textColor = UIColorFromRGB(0X42CDD9);
    }
    cell.titleLabel.text = model.recerdTypeName;
    cell.timeLabel.text = model.createTime;
    cell.priceLabel.text = [NSString stringWithFormat:@"%.2f",model.amount];
    return cell;
    
}


- (void )tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
   
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)backButtonClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)safeButtonClick:(id)sender {
    WalletSafeVC *vc = [[WalletSafeVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)cashClick:(id)sender {
    
    GetCashVC *vc = [[GetCashVC alloc]init];
    vc.totalPrice = self.priceLabel.text;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark -
#pragma mark 下拉刷新
- (void)downRefreshRequest //内部方法改
{
    __weak typeof(self) weakSelf = self;
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        
        weakSelf.page = kStartPage;
        [YJMSendRequest postDataWithParameters:@{@"pageSize":kNumOfPageSize,@"pageNo":[NSNumber numberWithInteger:weakSelf.page]} url:@"user/getUserMoneyRecord" result:^(NSDictionary *result, NSError *error) {
            result = [CommonUtils decryptDicWithResult:result];
            [self hideProgress:self.view animated:YES];
            if([result[@"result"] integerValue] == 1)
            {
                self.arrData = [NSMutableArray arrayWithArray:[TransactionListModel mj_objectArrayWithKeyValuesArray:result[@"data"][@"list"]]];
                if (weakSelf.arrData.count < kNumOfPageIntSize) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                    
                }else{
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
                [weakSelf.tableView.mj_header endRefreshing];
                
            }else{
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView.mj_footer endRefreshing];
                
                [CommonUtils showToast:[result objectForKey:@"msg"]];
            }
            if (self.arrData.count == 0) {
                [weakSelf.tableView noDataAddEmptyUIWithImageName:@"pic_emptystate_two" andEmptyText:@"暂无相关数据" andTopDistance:130];
            } else {
                [weakSelf.tableView haveDataRemoveEmptyUI];
            }
            [weakSelf.tableView reloadData];
        }];
    }];
    MJHEADER;
    
    
    self.tableView.mj_header = header;
    [self.tableView.mj_header beginRefreshing];
}
#pragma mark 上拉加载
- (void)upRefreshRequest //内部方法改
{
    __weak typeof(self) weakSelf = self;
    
    MJRefreshBackGifFooter *footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        
        
        [YJMSendRequest postDataWithParameters:@{@"pageSize":kNumOfPageSize,@"pageNo":[NSNumber numberWithInteger:weakSelf.page]} url:@"user/getUserMoneyRecord" result:^(NSDictionary *result, NSError *error) {
            result = [CommonUtils decryptDicWithResult:result];
            [self hideProgress:self.view animated:YES];
            if([result[@"result"] integerValue] == 1)
            {
                NSArray *arrTemp = [TransactionListModel mj_objectArrayWithKeyValuesArray:result[@"data"][@"list"]];
                [self.arrData addObjectsFromArray:arrTemp];
                if (arrTemp.count < kNumOfPageIntSize) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];

                }else{
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
                [weakSelf.tableView.mj_header endRefreshing];
                
            }else{
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView.mj_footer endRefreshing];
                
                [CommonUtils showToast:[result objectForKey:@"msg"]];
            }
            if (self.arrData.count == 0) {
                [weakSelf.tableView noDataAddEmptyUIWithImageName:@"pic_emptystate_two" andEmptyText:@"暂无相关数据" andTopDistance:130];
            } else {
                [weakSelf.tableView haveDataRemoveEmptyUI];
            }
            [weakSelf.tableView reloadData];
        }];
    }];
    
    MJFOOTER;
    self.tableView.mj_footer = footer;
    
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
